#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
根目录handle模块
'''

from lib.myweb import WebApplication
from lib.validate import Check

from common import auth
from common.myconfig import CONF
from common.myvalidate import ValidatorCommon
from common.mydata import ModelItem
from common.mydata import ModelUser


class ValidatorIndex(ValidatorCommon):
    '根模块专用校验器'
    @staticmethod
    @Check.is_empty
    @Check.is_len_range(6, 30)
    @Check.is_re_match(u'^[a-zA-Z0-9\u4E00-\u9FA5（）\(\)\-\/ ]*$')
    def check_query(target_str):
        '检查搜索语句'
        return True

    @staticmethod
    @Check.is_empty
    @Check.is_len_range(1, 6)
    @Check.is_alnum(False)
    def check_type(target_str):
        '检查搜索类型'
        return True

    @staticmethod
    @Check.is_empty
    @Check.is_len_range(1, 8)
    @Check.is_digit(True)
    def check_price_min(target_str):
        '检查价格范围'
        return True

    @staticmethod
    @Check.is_empty
    @Check.is_len_range(1, 8)
    @Check.is_digit(True)
    def check_price_max(target_str):
        '检查价格范围'
        return True


class HandleIndex(WebApplication):
    '根目录handle'
    _HANDLE_NAME = 'index'  # handle名称，用于模板前缀
    _PATH_PREFIX = ''  # 一级路径名称，用于解析path

    @auth.session(auth.SESSION_LEVEL['visitor'])
    def action_index(self):
        '主页'
        page_size = CONF['page_size']
        mod_itm = ModelItem()

        # 获取未卖的商品信息
        limits = (0, page_size)
        item_infos = mod_itm.select_by_available(limits)
        if not item_infos:
            item_infos = {}
        self._render.view['item_infos'] = item_infos

        # 获取所有符合条件的商品数量，供分页用
        item_count = mod_itm.count_by_available()
        self._render.view['item_count'] = item_count
        self._render.view['page_size'] = page_size

    @auth.session(auth.SESSION_LEVEL['visitor'])
    def action_search(self):
        '搜索页'
        page_size = CONF['page_size']
        num_start = 0

        self._render.view['page_size'] = page_size
        self._render.view['item_infos'] = {}
        self._render.view['item_count'] = 0
        self._render.view['search_info'] = {}

        # 检查参数
        query = self._request.query
        check_list = [
                'query',
                'type',
                'price_min',
                'price_max',
                ]
        search_info, error_type = ValidatorIndex.check_from_dict(
                query, check_list)

        if error_type:
            return self.error_type(error_type)

        # 查询语句相关参数
        query = search_info['query']
        search_type = search_info['type']
        limits = (num_start, page_size)

        # 价格相关参数
        price_min = search_info['price_min']
        price_max = search_info['price_max']
        price_min = int(price_min) if price_min else 0
        prices = [price_min, ]
        if price_max:
            prices.append(int(price_max))
        if len(prices) > 1 and prices[0] > prices[1]:
            # 如果价格没有交集，则可以跳过搜索
            prices = None
            query = ''

        # 设置搜索模式
        if query:
            case = search_type if search_type in ['name', 'tag'] else 'none'
        else:
            case = 'price' if prices else 'none'

        # 根据查询参数搜索商品信息
        mod_itm = ModelItem()
        switch_list = {
                'name': mod_itm.search_by_name,
                'tag': mod_itm.search_by_tags,
                'price': lambda x, y, z: mod_itm.search_by_price(z, y),
                'none': lambda x, y, z: None,
                }
        item_infos = switch_list[case](query, limits, prices)

        if not item_infos:
            item_infos = {}

        # 设置购买按钮
        for item_info in item_infos:
            item_info['special'] = 'buy' if not item_info['buyer_id'] else ''

        # 渲染变量准备
        self._render.view['item_infos'] = item_infos
        # 获取所有符合条件的商品数量，供分页用
        switch_list = {
                'name': mod_itm.count_by_search_name,
                'tag': lambda x, y: mod_itm.search_by_tags(x, None, y, True),
                'price': lambda x, y: mod_itm.count_by_search_price(y),
                'none': lambda x, y: 0,
                }
        item_count = switch_list[case](query, prices)

        self._render.view['search_info'] = search_info
        self._render.view['item_count'] = item_count

    @auth.session(auth.SESSION_LEVEL['visitor'])
    def action_psearch(self):
        '搜索页翻页，用json返回'
        page_size = CONF['page_size']
        num_max = CONF['num_max']
        num_start = 0

        self._render.mode = 'json'

        # 检查参数
        query = self._request.query
        check_list = [
                'query',
                'type',
                'price_min',
                'price_max',
                'offset',
                'num']
        search_info, error_type = ValidatorIndex.check_from_dict(
                query, check_list)

        if error_type:
            self._render.view = {'result': 'invalidate'}
            return

        # 查询语句相关参数
        query = search_info['query']
        search_type = search_info['type']

        # 翻页相关参数
        offset = search_info['offset']
        num = search_info['num']
        offset = int(offset) if offset else num_start
        num = int(num) if offset else page_size
        if num > num_max:
            num = num_max
        limits = (offset, num)

        # 价格相关参数
        price_min = search_info['price_min']
        price_max = search_info['price_max']
        price_min = int(price_min) if price_min else 0
        prices = [price_min, ]
        if price_max:
            prices.append(int(price_max))
        if len(prices) > 1 and prices[0] > prices[1]:
            # 如果价格没有交集，则可以跳过搜索
            prices = None
            query = ''

        # 设置搜索模式
        if query:
            case = search_type if search_type in ['name', 'tag'] else 'none'
        else:
            case = 'price' if prices else 'none'

        # 查询语句相关参数
        query = search_info['query']
        search_type = search_info['type']

        # 根据查询参数搜索商品信息
        mod_itm = ModelItem()
        switch_list = {
                'name': mod_itm.search_by_name,
                'tag': mod_itm.search_by_tags,
                'price': lambda x, y, z: mod_itm.search_by_price(z, y),
                'none': lambda x, y, z: None,
                }
        item_infos = switch_list[case](query, limits, prices)

        if not item_infos:
            item_infos = {}

        # 设置购买按钮
        for item_info in item_infos:
            item_info['special'] = 'buy' if not item_info['buyer_id'] else ''

        # 渲染变量准备
        self._render.view = {}
        if item_infos:
            self._render.view['result'] = 'ok'
            self._render.view['records'] = item_infos
        else:
            self._render.view['result'] = 'empty'

    @auth.session(auth.SESSION_LEVEL['user'])
    def action_user(self):
        '个人页，如果没有传入ID，则认为是看自己信息'
        page_size = CONF['page_size']
        offset_start = 0
        count_empty = 0
        self._render.view['page_size'] = page_size

        self._render.view['user_info'] = {}
        self._render.view['item_own_infos'] = {}
        self._render.view['item_own_count'] = count_empty
        self._render.view['item_buy_infos'] = {}
        self._render.view['item_buy_count'] = count_empty

        mod_itm = ModelItem()
        mod_usr = ModelUser()

        query = self._request.query
        user_info, error_type = ValidatorIndex.check_from_dict(
                query, ['id', ])
        if error_type:
            is_self = True
            user_id = self._session['user_info']['id']
        else:
            is_self = False
            user_id = user_info['id']
        self._render.view['is_self'] = is_self

        # 查找用户信息
        user_info = mod_usr.select_by_id(user_id)
        if not user_info:
            return self.error_type('not_exist')
        self._render.view['user_info'] = user_info

        # 获取拥有的商品信息
        limits = (offset_start, page_size)
        item_own_infos = mod_itm.select_by_owner(user_id, limits)
        if not item_own_infos:
            item_own_infos = {}
        self._render.view['item_own_infos'] = item_own_infos
        # 获取拥有的商品数量，供分页用
        item_own_count = mod_itm.count_by_owner(user_id)
        self._render.view['item_own_count'] = item_own_count
        # 如果是用户查看自己的商品，则再寻找买家信息
        if is_self:
            for item_own in item_own_infos:
                buyer_id = item_own['buyer_id']
                if buyer_id:
                    item_own['buyer_info'] = mod_usr.select_by_id(buyer_id)

        # 获取拥有的商品信息
        limits = (offset_start, page_size)
        item_buy_infos = mod_itm.select_by_buyer(user_id, limits)
        if not item_buy_infos:
            item_buy_infos = {}
        self._render.view['item_buy_infos'] = item_buy_infos
        # 获取拥有的商品数量，供分页用
        item_buy_count = mod_itm.count_by_buyer(user_id)
        self._render.view['item_buy_count'] = item_buy_count


application = HandleIndex()
